package cn.maidouya.pay.controller;

import cn.maidouya.order.domain.AdoptOrder;
import cn.maidouya.order.service.IAdoptOrderService;
import cn.maidouya.pay.config.AlipayConfig;
import cn.maidouya.pay.constants.OrderConstants;
import cn.maidouya.pay.domain.AlipayInfo;
import cn.maidouya.pay.domain.PayBill;
import cn.maidouya.pay.domain.PayFlow;
import cn.maidouya.pay.mapper.PayFlowMapper;
import cn.maidouya.pay.service.IAlipayInfoService;
import cn.maidouya.pay.service.IPayBillService;
import cn.maidouya.pay.service.IPayFlowService;
import cn.maidouya.quartz.constants.QuartzConstants;
import cn.maidouya.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.print.attribute.standard.JobName;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IAdoptOrderService adoptOrderService;
    @Autowired
    private IPayFlowService payFlowService;
    @Autowired
    private IQuartzService quartzService;
    /**
     *   异步回调地址
     * @param request
     */
    @PostMapping("/notify")
    public void notify(HttpServletRequest request){
        System.out.println("进入支付");
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr);
                params.put(name, valueStr);
            }
            /**
             * 获取统一支付单号
             * 校验统一支付订单
             *  统一支付单号获取对应店铺
             */
            String unionPaySn = params.get("out_trade_no");
            PayBill bill = payBillService.loadByUnionPaySn(unionPaySn);
            AlipayInfo info = alipayInfoService.getByShopId(bill.getShop_id());

            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params, info.getAlipay_public_key(),
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
            //验证成功
            if(signVerified) {
                String out_trade_no = unionPaySn; //商户订单号
                String trade_no = new String(request.getParameter("trade_no")); //支付宝交易号
                String trade_status = new String(request.getParameter("trade_status"));//交易状态

                    if(trade_status.equals("TRADE_FINISHED")){
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    }else if (trade_status.equals("TRADE_SUCCESS")){
                        // 1. 修改订单状态
                        bill.setState(1);
                        payBillService.update(bill);
                        // 2. 修改业务状态
                            if (OrderConstants.BUSINESS_TYPE_ACQUISITION_ORDER.equals(bill.getBusinessType())){
                                AdoptOrder adoptOrder = adoptOrderService.loadById(bill.getBusinessKey());
                                adoptOrder.setState(1);
                                adoptOrderService.update(adoptOrder);

                                //支付成功之后，删除定时任务
                                String JobName = QuartzConstants.ORDER_ADOPT_CANCEL_PREFIX + adoptOrder.getPaySn();
                                quartzService.removeJob(JobName);
                                System.out.println(JobName + "删除定时删除任务");

                                // 3. 领养宠物记录流水
                                payBillService.saveFlow(bill);

                            }else if (OrderConstants.BUSINESS_TYPE_PRODUCT_ORDER.equals(bill.getBusinessType())){
                                // 4. 服务记录流水
                                payBillService.saveFlow(bill);
                            }
                    }
            }else {//验证失败
                System.out.println("下单失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}